package com.example.demo.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.example.demo.entity.dataSource1.MemberEntity;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * Created by wen.gao on 2018/5/9.
 */
@Configuration
@EnableTransactionManagement
//@EnableJpaRepositories(basePackages = "com.example.demo.data.repository",entityManagerFactoryRef = "firstEntityManagerFactory",transactionManagerRef="firstTransactionManager")
//@EnableJpaRepositories(basePackageClasses = MemberEntity.class , entityManagerFactoryRef = "firstEntityManagerFactory",transactionManagerRef="firstTransactionManager")
@MapperScan(basePackages = "com.example.demo.dao.dataSource1", sqlSessionTemplateRef  = "firstSqlSessionTemplate")
public class DataSource1Config {
    @Bean
    @ConfigurationProperties("datasource.first")
    @Primary
    public DataSourceProperties firstDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name="firstDataSource")
    @ConfigurationProperties("datasource.first")
    @Primary
    public DataSource firstDataSource() throws Exception{
//        return firstDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
//        DataSource dataSource1 = DataSourceBuilder.create().build();
        HikariDataSource dataSource = firstDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();

        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
        mysqlXaDataSource.setUrl(dataSource.getJdbcUrl());
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
        mysqlXaDataSource.setPassword(dataSource.getPassword());
        mysqlXaDataSource.setUser(dataSource.getUsername());
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setUniqueResourceName("firstDataSource");
        xaDataSource.setTestQuery(dataSource.getConnectionTestQuery());

        /*
        xaDataSource.setMinPoolSize(dataSource.getMinimumIdle());
        xaDataSource.setMaxPoolSize(dataSource.getMaximumPoolSize());
        xaDataSource.setMaxLifetime((int)dataSource.getMaxLifetime());
        xaDataSource.setBorrowConnectionTimeout((int)dataSource.getConnectionTimeout());
        xaDataSource.setLoginTimeout(dataSource.getLoginTimeout());
//        xaDataSource.setMaintenanceInterval(dataSource.get);
//        xaDataSource.setMaxIdleTime(dataSource.getId);
        xaDataSource.setTestQuery(dataSource.getConnectionTestQuery());
        */
        return xaDataSource;
    }

///**
// * 此处大段被注释掉的内容为Spring-data-jpa(Hibernate)
// * */
//    /**
//     * 实体管理对象
//     * @param builder1 由spring注入这个对象，首先根据type注入（多个就取声明@Primary的对象），否则根据name注入
//     * @return
//     */
//    @Bean
//    @Primary
//    public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory(EntityManagerFactoryBuilder builder1) {
//        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//        vendorAdapter.setGenerateDdl(false);// 不自动建表
//        return builder1
//                .dataSource(firstDataSource())
//                .packages(MemberEntity.class)
//                .persistenceUnit("firstDataSource")
//                .build();
//    }
//
//    /**
//     * 事务管理对象
//     * @return
//     */
//    @Bean(name = "firstTransactionManager")
//    @Primary
//    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
//        JpaTransactionManager transactionManager = new JpaTransactionManager();
//        transactionManager.setEntityManagerFactory(emf);
//        return transactionManager;
//    }
//
//    @Bean
//    @Primary
//    public JdbcTemplate jdbcTemplate(){
//        return new JdbcTemplate(firstDataSource());
//    }
//
//    @Bean
//    @Primary
//    public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){
//        return new TransactionTemplate(platformTransactionManager);
//    }

/****************************************************************************************************************************************************************************************
 * Mybatis Start
 ****************************************************************************************************************************************************************************************/

    @Bean(name = "firstSqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/dataSource1/*.xml"));
        return bean.getObject();
    }
// 尝试使用xatx替代JTATransactionManager
//    @Bean(name = "firstTransactionManager")
//    @Primary
//    public DataSourceTransactionManager testTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

    @Bean(name = "firstSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
